<?php 
namespace app\mall\model;
use think\Model;
use think\Db;
class GoodsCategory extends Model{
	protected $pk = 'id';
	protected $table = 'ys_goods_category';
    protected $field = true;        //自动忽略不存在的字段
	protected $validate = [
		['title', 'require|max:50', '分类标题不能为空'],
	];
    
	protected function initialize(){
        parent::initialize();
    }

    /**
     * 添加商品分类
     * @lingyun 2017-10-27
     */
    public function add($data){
    	$result = $this->validate($this->validate)->save($data);
    	if(!$result){
    		return ['code'=>0,'msg'=>$this->getError()];
    	}
    	return ['code'=>1,'msg'=>'添加成功！'];
    }

    /**
     * 编辑商品分类
     * @lingyun 2017-10-27
     */
    public function edit($data,$id){
        try{
            $result =  $this->validate($this->validate)->save($data,['id'=>$id]);
            if(false === $result){
                return ['code' => 0, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '编辑成功'];
            }
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }
    /**
     * 设置状态
     * @return [type] [description]
     */
    public function setstatus($data,$id){
    	try{
    		$result = $this->validate(false)->save($data,['id'=>$data['id']]);
    		if(false === $result){
                return ['code' => 0, 'data' => '', 'msg' => '设置失败'];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '设置成功'];
            }
    	}catch(PDOException $e){
    		return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
    	}
    }
    /**
     * 删除门店
     * @return [type] [description]
     */
    public function del($id){
        $result = $this->where('pid',$id)->count();
        $result1 = Db::name('goods')->where('cat_id',$id)->count();
        if($result>0){
            return ['code'=>0,'data'=>'','msg'=>'该分类下有分类不能删除'];
        }
        if($result1>0){
            return ['code'=>0,'data'=>'','msg'=>'该分类下有商品，不能删除'];
        }
        $res = $this->where('id',$id)->delete();
        if($res>0){
            return ['code'=>'1','data'=>'','msg'=>'删除成功'];
        }else{
            return ['code'=>'0','data'=>'','msg'=>'删除失败'];
        }
    }

    
}
?>